<template>
<div class="movie-list">
    <MovieItem v-for="item in state.movieList" :key="item.id" :movie="item" />
</div>
</template>

<script>
import {
    inject,
    onMounted,
    onUnmounted
} from "vue"
import store from "../store"
import MovieItem from "../components/MovieItem"
import {
    getCategoryMovie,
    getSearchMovie
} from "../utils/fetchData"
export default {
    name: "home",
    components: {
        MovieItem,
    },
    setup() {
        const state = inject(store.stateProvide)
        onMounted(() => {
            window.addEventListener("scroll", scrollLoading.bind(this, state), false)
        })
        onUnmounted(() => {
            window.removeEventListener("scroll", scrollLoading.bind(this, state), false)
        })
        return {
            state
        }
    }
}

function scrollLoading(state) {
    let scrollHeight = Math.max(document.documentElement.scrollHeight, document.body.scrollHeight);
    let windowHeight = window.innerHeight;
    //滚动条滚动距离
    let scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
    if (scrollTop + windowHeight + 100 > scrollHeight && state.currentPage * 10 < state.count) {
        if (state.isSearch) {
            // 搜索数据:
            getSearchMovie(state.searchKey, state, true)

        } else {
            getCategoryMovie(state.currentCate, state, true)
        }
    }
}
</script>

<style lang="sass" scoped>
@import "@/assets/styles/views/home.scss"
</style>
